import { defineStore } from 'pinia'
import { ref } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { HtmlModulesPath } from '@/utils/constants'
import { useLanguageStore } from '@/stores/language'
import { biBridge } from '@/appox/bi-bridge'

export const usePageDialogStore = defineStore('pageDialog', () => {
  const dialogQueue = new DialogQueue()
  const currentDialog = ref(null)
  const embedderEntryName = ref('')
  const embedderBridgeId = ref('')
  const embedderWebStyleHeight = ref(null)
  const dialogStyle = ref({width: '650px', height: '500px'})

  async function show(entryName, viewConfig, showHelpForHtmlModules) {
    return dialogQueue.show({
      onLoaded: async () => {
        currentDialog.value = {
          title: (useLanguageStore().isChinese ? 'HTML模块: ' : 'HTML Module: ') + entryName,
        }

        const htmlModuleInstInfo = await biBridge.initializeModule(HtmlModulesPath, entryName, viewConfig, showHelpForHtmlModules)
        embedderEntryName.value = entryName
        embedderBridgeId.value = htmlModuleInstInfo.bridgeId
        embedderWebStyleHeight.value = htmlModuleInstInfo.webStyleHeight
        dialogStyle.value = {width: (htmlModuleInstInfo.webStyleWidth + 32) + 'px', height: (htmlModuleInstInfo.webStyleHeight + 72) + 'px'}
      },
      onHidden: () => {
        biBridge.releaseModule(embedderBridgeId.value)
        embedderEntryName.value = ''
        embedderBridgeId.value = ''
        embedderWebStyleHeight.value = null
      }
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    title: () => currentDialog.value?.title || '',
    embedderEntryName,
    embedderBridgeId,
    embedderWebStyleHeight,
    dialogStyle,
    // 动作
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 